package org.framework.lazy.cloud.network.heartbeat.common;

import io.netty.channel.Channel;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 服务端存储 channel 上下文
 */
public class NettyServerContext {


    protected static final ConcurrentHashMap<String/*clientId*/, List<NettyClientChannel>/*NettyClientChannel*/>
            NETTY_CLIENT_CHANNEL_SOCKET = new ConcurrentHashMap<>();


    /**
     * 添加访客
     *
     * @param clientId 客户端ID
     * @param channel  channel
     */
    public static <T> void pushServerEndpointChannel(String clientId, Channel channel) {
        List<NettyClientChannel> nettyClientChannelList = getServerEndpointChannels(clientId);
        // 关闭旧的通道
        nettyClientChannelList.forEach(nettyClientChannel -> {
            Channel oldChannel = nettyClientChannel.getChannel();
            if (oldChannel != null && oldChannel.isActive()) {
                oldChannel.close();
            }
        });
        List<NettyClientChannel> activeNettyClientChannelList = nettyClientChannelList
                .stream()
                .filter(nettyClientChannel ->
                        nettyClientChannel.getClientId().equals(clientId) && nettyClientChannel.getChannel().isActive())
                .collect(Collectors.toList());
        NettyClientChannel nettyClientChannel = new NettyClientChannel(clientId, channel);
        activeNettyClientChannelList.add(nettyClientChannel);
        NETTY_CLIENT_CHANNEL_SOCKET.put(clientId, activeNettyClientChannelList);
    }

    /**
     * 通过客户端ID获取客户端使用的访客socket
     *
     * @param clientId 客户端ID
     * @return 客户端通道
     */
    public static List<NettyClientChannel> getServerEndpointChannels(String clientId) {
        return NETTY_CLIENT_CHANNEL_SOCKET.getOrDefault(clientId, new ArrayList<>());
    }

    /**
     * 通过客户端ID获取客户端使用的访客socket
     *
     * @return 客户端通道
     */
    public static List<NettyClientChannel> getServerEndpointChannels() {
        return NETTY_CLIENT_CHANNEL_SOCKET
                .values()
                .stream()
                .collect(Collectors.flatMapping(Collection::stream, Collectors.toList()));
    }


    /**
     * 移除 客户端通道
     *
     * @param clientId 客户端ID
     */
    public static void removeServerEndpointChannels(String clientId) {
        for (NettyClientChannel nettyClientChannel : getServerEndpointChannels(clientId)) {
            if (nettyClientChannel.getChannel() != null && nettyClientChannel.getChannel().isActive()) {
                nettyClientChannel.getChannel().close();
            }
        }
        NETTY_CLIENT_CHANNEL_SOCKET.remove(clientId);
    }


}
